package com.jingfu.util;

import com.jingfu.dto.UserDetail;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.MapCache;

import javax.swing.text.html.Option;
import java.util.Optional;

/**
 * @author jingfuu@163.com
 * @version v1.0
 * @date 2022/1/20 下午1:54
 **/
public class UserUtil {
    private static MapCache<String,Object> mapCache = (MapCache) SpringUtils.getBean("memoryCache");

    /**
     * 获取当前登录用户
     * @return
     */
    public static Optional<UserDetail> getCurrentUser() {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        UserDetail userDetail = (UserDetail) mapCache.get(username);
        return Optional.ofNullable(userDetail);
    }

    /**
     * 获取指定用户名中的缓存用户信息
     * @param username
     * @return
     */
    public static Optional<UserDetail> getCacheUserByName(String username) {
        UserDetail userDetail = (UserDetail) mapCache.get(username);
        return Optional.ofNullable(userDetail);
    }

    /**
     * 缓存当前用户
     * @param username
     * @param userDetail
     */
    public static void cacheUser(String username, UserDetail userDetail) {
        mapCache.put(username,userDetail);
    }

    /**
     * 清除指定用户信息缓存
     * @param username
     */
    public static void  clearUserCache(String username){
        mapCache.remove(username);
    }
}
